上一篇介紹了K-means的運作機制,接下來我們進入實作的部分。
首先,因為我們是GIS實作,所以分類的對象是影像,因此我們希望可以做到以下的流程:
我們使用的函式庫scikit-learn函式庫,有很多機器學習的工具,從上述這張地圖可以知道scikit-learn機器學習的使用時機。
import skimage
import skimage.io
import skimage.external
from sklearn import cluster
import numpy
def image_kmeans_classification(image_array,bands):
image_array = numpy.asarray(image_array)
row_number = image_array.shape[0]
col_number = image_array.shape[1]
sample = image_array.reshape((row_number*col_number,bands))
kmeans_classifer = cluster.KMeans(n_clusters = 4,random_state=0).fit(sample)
kmeans_result = kmeans_classifer.predict(sample)
kmeans_result = (kmeans_result-numpy.min(kmeans_result))/(numpy.max(kmeans_result)-numpy.min(kmeans_result))*255
image_array_classification = kmeans_result.reshape((row_number,col_number))
return image_array_classification
def main():
image_path = r"D:\Nantou County-Ren ai Township-D043-UAV ladir data\DEM TO TXT\37ne2_feature.tif"
output_image_path = r"D:\Nantou County-Ren ai Township-D043-UAV ladir data\DEM TO TXT\37ne2_feature_result.tif"
bands = 4
image_array = skimage.io.imread(image_path)
image_array_classification = image_kmeans_classification(image_array,bands)
#(jpg﹑png) skimage.io.imsave(output_image_path,image_array_classification)
skimage.external.tifffile.imsave(output_image_path,image_array_classification)
if __name__ == "__main__":
main()
原圖
圖來源:鐵人賽
成果
skikit-learn Choosing the right estimator